package net.sahv.bdyz.controller.admin;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import net.sahv.bdyz.model.Pattern;
import net.sahv.bdyz.model.PatternFilter;
import net.sahv.bdyz.model.ShowSynchronization;
import net.sahv.bdyz.model.Theme;
import net.sahv.bdyz.service.PatternFilterService;
import net.sahv.bdyz.service.PatternService;
import net.sahv.bdyz.service.ShowSynchronizationService;
import net.sahv.bdyz.service.ThemeService;
import net.sahv.bdyz.util.ImgCompress;
import net.sahv.bdyz.util.LoadCfgUtil;
import net.sahv.bdyz.util.PagingUtil;

/**
 * @author 作者 : 周晓娜
 * @date 创建时间：2016年8月8日 下午2:59:59
 * @version 1.0
 * @see
 */
@Controller
@RequestMapping(value = "admin/Patterns/")
public class PatternsController {
	@Autowired
	private PatternService patternService;//花型列表
	@Autowired
	private PatternFilterService patternFilterService;//花型属性
	@Autowired
	private ThemeService themeService;//主题	
	@Autowired
	private ShowSynchronizationService showSynchronizationService;//秀场同步表

	/**
	 * 花型列表页面 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月10日 上午10:01:43
	 * @param
	 * @parameter
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value = "/Index",method=RequestMethod.GET)
	public String Index(Model model) throws FileNotFoundException, IOException {
		List<PatternFilter> ffList = patternFilterService.selectAllByParentName("类别");
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		
		model.addAttribute("imgpath",mapUrls.get("targetUrl.img"));
		model.addAttribute("parent", ffList);
		return "admin/patterns/list";
	}

	/**
	 * 上传图片页面
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月10日 上午10:01:28
	 * @param
	 * @parameter
	 * @return
	 */
	@RequestMapping(value = "/insertImage",method=RequestMethod.GET)
	public String insertImage() {
		return "admin/patterns/insertImg";
	}

	/**
	 * 修改编号和尺寸页面
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:56:30
	 * @param
	 * @parameter
	 * @return
	 */
	@RequestMapping(value="/EditNoAndCC",method=RequestMethod.GET)
	public String EditNoAndCC(Integer id, Model model) {
		Pattern ffList = patternService.selectByPrimaryKey(id);
		model.addAttribute("parent", ffList);
		return "admin/patterns/updateNoAndCC";
	}

	/**
	 * 修改销售区页面
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:58:12
	 * @param
	 * @parameter
	 * @return
	 */
	@RequestMapping(value="/EditVip",method=RequestMethod.GET)
	public String EditVip(int[] id, Model model) {
		String pIds = Arrays.toString(id);
		if (pIds.length() > 0) {
			pIds = pIds.substring(1, pIds.length() - 1);
		}
		model.addAttribute("pIds", pIds);
		return "admin/patterns/updateVip";
	}

	/**
	 * 修改花型的属性页面
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:59:09
	 * @param
	 * @parameter
	 * @return
	 */
	@RequestMapping("/EditFilter")
	public String EditFilter(String id, Model model) {
		List<PatternFilter> color = patternFilterService.selectAllByParentName("颜色");
		List<PatternFilter> element = patternFilterService.selectAllByParentName("元素");
		List<PatternFilter> category = patternFilterService.selectAllByParentName("类别");
		List<PatternFilter> location = patternFilterService.selectAllByParentName("花位");
		List<Theme> theme = (List<Theme>)themeService.findThemeList();
		List<ShowSynchronization> show = showSynchronizationService.findAllChild();
		for (PatternFilter map : color) {
			String a = map.getPtName().substring(4,map.getPtName().length()-3);
			map.setPtName(a);
		}
		// Pattern ffList =
		// patternService.selectByPrimaryKey(Integer.parseInt(id));
		// model.addAttribute("parent1", ffList);
		model.addAttribute("parent", id);
		model.addAttribute("color", color);
		model.addAttribute("element", element);
		model.addAttribute("category", category);
		model.addAttribute("location", location);
		model.addAttribute("theme", theme);
		model.addAttribute("show", show);
		return "admin/patterns/updateFilter";
	}
	/**
	 * 花型预设标签
	 * @author 薛国计
	 * @date 2016年10月6日
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/EditFilter2")
	public String EditFilter2(String id, Model model) {
		List<PatternFilter> yushe = patternFilterService.selectAllYushe();
		Pattern ffList = patternService.selectByPrimaryKey(Integer.parseInt(id));
		model.addAttribute("parent1", ffList);
		model.addAttribute("parent", id);
		model.addAttribute("yushe", yushe);
		return "admin/patterns/updateFilter2";
	}

	/**
	 * 花型列表方法
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月10日 上午10:01:56
	 * @param
	 * @parameter
	 * @return
	 */
	@RequestMapping(value = "PatternList", method = RequestMethod.POST)
	@ResponseBody
	public JSON PatternList(PagingUtil pagingUtil, HttpServletRequest request, Model model) {
		Map<String, Object> param = new HashMap<String, Object>();

		param.put("start", pagingUtil.getiDisplayStart());
		param.put("length", pagingUtil.getiDisplayLength());
		String pNo = request.getParameter("P_NO");// 编号
		String pCategory = request.getParameter("P_CATEGORY");// 类别
		String pVip = request.getParameter("P_VIP");// 销售区
		String where = " where P_IS_DELETE=0 ";
		if (pNo != null && !pNo.equals("")) {
			where += " and P_NO like '%" + pNo + "%' ";
		}
		if (pCategory != null && !pCategory.equals("")) {
			where += " and P_CATEGORY=" + pCategory;
		}
		if (pVip != null && !pVip.equals("")) {
			where += " and P_VIP=" + pVip;
		}
		param.put("where", where);// 条件
		param.put("sortField", " order by P_CREATE_TIME desc");// 条件
		List<Map<String, Object>> patternList = patternService.getList(param);

		Integer patternListCount = patternService.getTotalCount(where);// 统计信息的总条数

		for (Map<String, Object> map : patternList) {
			if (map.get("P_COLOR") == null) {
				map.put("P_COLOR", "");// 颜色
			} else {
				List<PatternFilter> colorList = patternFilterService
						.getListByIds("(" + map.get("P_COLOR").toString() + ")");
				String color = "";
				for (PatternFilter pf : colorList) {
					color += pf.getPtName() + ",";
				}
				map.put("P_COLOR", color.substring(0, color.length() - 1));
				// map.put("P_COLOR",
				// patternFilterService.selectByPrimaryKey(Integer.parseInt(map.get("P_COLOR").toString())).getPtName());//
				// 颜色
			}

			if (map.get("P_ELEMENT") == null) {
				map.put("P_ELEMENT", "");// 元素
			} else {
				List<PatternFilter> eleList = patternFilterService
						.getListByIds("(" + map.get("P_ELEMENT").toString() + ")");
				String ele = "";
				for (PatternFilter pf : eleList) {
					ele += pf.getPtName() + ",";
				}
				map.put("P_ELEMENT", ele.substring(0, ele.length() - 1));
			}

			if (map.get("P_CATEGORY") == null) {
				map.put("P_CATEGORY", "");// 类别
			} else {
				List<PatternFilter> cateList = patternFilterService
						.getListByIds("(" + map.get("P_CATEGORY").toString() + ")");
				String cate = "";
				for (PatternFilter pf : cateList) {
					cate += pf.getPtName() + ",";
				}
				map.put("P_CATEGORY", cate.substring(0, cate.length() - 1));
			}

			if (map.get("P_LOCATION") == null) {
				map.put("P_LOCATION", "");// 花位
			} else {
				List<PatternFilter> locationList = patternFilterService
						.getListByIds("(" + map.get("P_LOCATION").toString() + ")");
				String location = "";
				for (PatternFilter pf : locationList) {
					location += pf.getPtName() + ",";
				}
				map.put("P_LOCATION", location.substring(0, location.length() - 1));
			}

			if(map.get("P_VIP") != null && map.get("P_VIP").toString().equals("1"))
			{
				map.put("P_VIP", "共享区");
			}
			if(map.get("P_VIP") != null && map.get("P_VIP").toString().equals("2"))
			{
				map.put("P_VIP", "vip专区");
			}
			if(map.get("P_VIP") != null && map.get("P_VIP").toString().equals("3"))
			{
				map.put("P_VIP", "新上传");
			}
			if(map.get("P_VIP") != null && map.get("P_VIP").toString().equals("4"))
			{
				map.put("P_VIP", "已下架");
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("aaData", patternList);
		// 查出来总共有多少条记录
		map.put("iTotalRecords", patternListCount);
		map.put("iTotalDisplayRecords", patternListCount);
		map.put("sEcho", pagingUtil.getsEcho());

		return (JSON) JSON.toJSON(map);
	}

	/**
	 * 上传图片方法
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月10日 上午10:02:05
	 * @param
	 * @parameter
	 * @return
	 * @throws Exception 
	 * @throws FileNotFoundException 
	 */
	@ResponseBody
	@RequestMapping(value = "/insertImage", method = RequestMethod.POST)
	public ApiResult insertImage(String returnImgArray,HttpServletRequest request) throws FileNotFoundException, Exception {
		ApiResult result = new ApiResult();
		//ImagePHash push = new ImagePHash();
		// 多图上传字符串分割
		String[] returnImgArrayString = returnImgArray.split("\\|");
		// 多图上传
		int flag = 0;
		for (String returnImg : returnImgArrayString) {
			if (returnImg.equals("")){

			} else {
				//排除重复上传选项
				int count=patternService.selectCountByPImg(returnImg.split(",")[0].split("/")[3]);
				if(count>=1){
					result.msg.status = 2;
					result.msg.desc = "重复提交！";
					return result;
				}else{
					Pattern dMoreImage = new Pattern();
					//String realPath = request.getServletContext().getRealPath("/upload/"+returnImg);
					//String imgSerial=push.getHash(new FileInputStream(new File(realPath)));
					String imgSerial=returnImg.split(",")[2];
					dMoreImage.setpImg(returnImg.split(",")[0].split("/")[3]);
					dMoreImage.setpMessage1(imgSerial);
					dMoreImage.setpCreateTime(new Date());
					dMoreImage.setpIsDelete(0);
					flag = flag + patternService.upImg(dMoreImage);
				}
				
			}
		}

		if (flag > 0) {
			result.msg.status = 0;
			result.msg.desc = "添加成功！";
		} else {
			result.msg.status = 1;
			result.msg.desc = "添加失败！";
		}
		return result;
	}

	/**
	 * 批量删除
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:11:20
	 * @param
	 * @parameter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/Deletes", method = RequestMethod.POST)
	public ApiResult Deletes(String id) {
		ApiResult result = new ApiResult();
		int flag = 0;
		if (id.length() > 0) {
		}
		String[] returnImgArrayString = id.split("\\,");
		for (String returnImg : returnImgArrayString) {
			if (returnImg.equals("")) {

			} else {
				flag = flag + patternService.DeleteById(Integer.parseInt(returnImg));
			}
		}
		if (flag > 0) {
			result.msg.status = 0;
			result.msg.desc = "删除成功！";
		} else {
			result.msg.status = 1;
			result.msg.desc = "删除失败！";
		}
		return result;
	}

	/**
	 * 修改编号和尺寸
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:29:45
	 * @param
	 * @parameter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/UpdateNoAndCC", method = RequestMethod.POST)
	public ApiResult UpdateNoAndCC(Pattern record) {
		ApiResult result = new ApiResult();
		int flag = patternService.updateNoAndCC(record);
		if (flag > 0) {
			result.msg.status = 0;
			result.msg.desc = "修改成功！";
		} else {
			result.msg.status = 1;
			result.msg.desc = "修改失败！";
		}
		return result;
	}

	/**
	 * 修改销售区
	 * 
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:29:32
	 * @param
	 * @parameter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/UpdateVip", method = RequestMethod.POST)
	public ApiResult UpdateVip(String pId, Integer pVip) {
		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "修改失败！";
		if (pId != null && pId != "" && pVip != null) {
			int flag = patternService.updateVip(pId, pVip);
			if (flag > 0) {
				List<Pattern> list = patternService.getById(pId);
				for (Pattern p : list) {
					p.setTiaojian(p.getpType() + "," + p.getpColor() + "," + p.getpElement() + "," + p.getpCategory()
							+ "," + p.getpLocation() + "," + (p.getpVip() == null ? "" : "0" + p.getpVip()));
					patternService.updateTiaoJian(p);
				}
					result.msg.status = 0;
					result.msg.desc = "修改成功！";
			}
		}
		return result;
	} 	

	/**
	 * 修改花型的属性	  
	 * @author 作者 : 周晓娜
	 * @date 创建时间：2016年8月11日 上午9:34:40
	 * @param
	 * @parameter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/UpdateFilter", method = RequestMethod.POST)
	public ApiResult UpdateFilter(Pattern record, HttpServletRequest request) {
		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "修改失败！";
		int flag = 0;		
		String[] returnImgArrayString = request.getParameter("pIds").split("\\,");//选择的IDs
		for (String returnImg : returnImgArrayString) {
			if (returnImg.equals("")) {

			} else {
				record.setpId(Integer.parseInt(returnImg));
				Pattern list = patternService.selectByPrimaryKey(record.getpId());
				list.setpColor(record.getpColor());
				list.setpElement(record.getpElement());
				list.setpCategory(record.getpCategory());
				list.settId(record.gettId());
				list.setSsId(record.getSsId());
				list.setpLocation(record.getpLocation());
				list.setpBuyoutPrice(record.getpBuyoutPrice());
				record.setpVip(list.getpVip());
				list.setTiaojian(record.getpType() + "," + record.getpColor() + "," + record.getpElement() + ","
						+ record.getpCategory() + "," + record.getpLocation() + ","
						+ (record.getpVip() == null ? "" : "0" + record.getpVip()));
				flag = patternService.updateByPrimaryKey(list);
				
			}
		}//传过来的ID，挨个修改记录
		if (flag > 0) {
			result.msg.status = 0;
			result.msg.desc = "修改成功！";
		}
		return result;
	}
	@ResponseBody
	@RequestMapping(value = "/UpdateFilter2", method = RequestMethod.POST)
	public ApiResult UpdateFilter2(Pattern record, HttpServletRequest request) {
		ApiResult result = new ApiResult();
		Pattern list = patternService.selectByPrimaryKey(record.getpId());
		
		list.setpMessage2(record.getpMessage2());
		int flag = patternService.updateByPrimaryKey(list);
		if (flag > 0) {
			result.msg.status = 0;
			result.msg.desc = "修改成功！";
		}
		return result;
	}
	/**
	 * 花型编号查询唯一
	 * @author 薛国计
	 * @date 2016年8月18日
	 * @param pNo
	 * @param pId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/chakan", method = RequestMethod.POST)
	public ApiResult chakan(String pNo,Integer pId) {
		ApiResult result = new ApiResult();
		Pattern pattern = patternService.selectByNo(pNo);
		if(pattern!=null){
			if(!pattern.getpId().equals(pId)){
				result.msg.status = 1;
			}
		}
		return result;
	}
	
	/**
	 * 批量生成缩略图
	 * @author 张天敏
	 * @date 日期：2016年10月10日 时间：下午4:56:13
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	@RequestMapping(value="/thumbnail")
	public ApiResult thumbnail(HttpServletRequest request) throws FileNotFoundException, IOException{
		ApiResult result=new ApiResult();
		//查询全部的花型数据
		List<Pattern> patternListAll=patternService.selectAll();
		//循环遍历,将花型数据中的花型名称放入list容器中
		List<String> imgList=putArrayList(patternListAll);
		//输入，输出，花型路径拼接
		List<Map<String, String>> imgUrlList=appendImgUrlList(imgList,request);
		
		boolean flag=createThumbnail(imgUrlList,request);
		if(flag){
			result.msg.status=0;
		}
		return result;
	}

	/**
	 * @author 张天敏
	 * @date 日期：2016年10月10日 时间：下午5:14:35
	 * @param imgUrlList
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	private boolean createThumbnail(List<Map<String, String>> imgUrlList,
			HttpServletRequest request) throws FileNotFoundException, IOException {
		
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String proString=mapUrls.get("compressionRatio.nomal");
		
		//压缩比例
		Integer pro=Integer.valueOf(proString);
		
		for(Map<String, String> imgUrl:imgUrlList){
			//生成面料压缩图片
			ImgCompress.initCompression(imgUrl.get("inputPath"), imgUrl.get("outputPath"), pro);
		}
		
		return true;
	}

	/**
	 * 花型路径拼接
	 * @author 张天敏
	 * @date 日期：2016年10月10日 时间：下午5:09:25
	 * @param imgList
	 * @param request 
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	private List<Map<String, String>> appendImgUrlList(List<String> imgList, HttpServletRequest request) throws FileNotFoundException, IOException {
		List<Map<String,String>> imgUrlList=new ArrayList<Map<String,String>>();
		Map<String, String> mapUrls = LoadCfgUtil.loadCfg();
		String imgParent = mapUrls.get("targetUrl.img");
		String compression=mapUrls.get("local.uploadImgPath.compression");
		for(String imgString:imgList){
			//传入图片的路径
			String inputPath=imgParent+imgString;
			//输出图片的路径
			String outputPath=request.getServletContext().getRealPath(compression+imgString);
			Map<String,String> map=new HashMap<String,String>();
			map.put("inputPath", inputPath);
			map.put("outputPath", outputPath);
			imgUrlList.add(map);
		}
		return imgUrlList;
	}

	/**
	 * 循环遍历,将花型数据中的花型名称放入list容器中
	 * @author 张天敏
	 * @param patternListAll 
	 * @return 
	 * @date 日期：2016年10月10日 时间：下午5:02:07
	 */
	private List<String> putArrayList(List<Pattern> patternListAll) {
		List<String> imgList=new ArrayList<String>();
		for(Pattern pattern:patternListAll){
			//将花型数据中的花型名称放入list容器中
			imgList.add(pattern.getpImg());
		}
		return imgList;
	}
	
	
	
	
}
